/**
 * Simple API Security Middleware
 *
 * 轻量级本地API安全中间件，专为本地MCP工具设计
 * 替换过度设计的企业级安全中间件
 */

class SimpleAPISecurity {
    constructor(options = {}) {
        this.options = {
            // 简化的配置选项
            enableCORS: options.enableCORS !== false,
            enableSecurityHeaders: options.enableSecurityHeaders !== false,
            maxRequestSize: options.maxRequestSize || 10 * 1024 * 1024, // 10MB
            ...options
        };
    }

    /**
     * 主要的安全中间件
     */
    middleware() {
        return (req, res, next) => {
            try {
                // 应用安全头部
                if (this.options.enableSecurityHeaders) {
                    this.applyBasicSecurityHeaders(res);
                }

                // 应用CORS，如果返回false表示应该停止处理
                if (this.options.enableCORS) {
                    if (!this.applyCORS(req, res)) {
                        return; // OPTIONS请求已处理
                    }
                }

                // 基本请求验证
                if (!this.validateBasicRequest(req, res)) {
                    return;
                }

                next();
            } catch (error) {
                console.error('Security middleware error:', error);
                res.status(500).json({
                    error: 'Internal security error',
                    code: 'SECURITY_ERROR'
                });
            }
        };
    }

    /**
     * 应用基本的安全头部
     */
    applyBasicSecurityHeaders(res) {
        // 只保留最关键的安全头部
        res.setHeader('X-Content-Type-Options', 'nosniff');
        res.setHeader('X-Frame-Options', 'DENY');
        res.setHeader('X-XSS-Protection', '1; mode=block');
        res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
    }

    /**
     * 应用CORS（跨域资源共享）
     */
    applyCORS(req, res) {
        const origin = req.headers.origin;

        // 对于本地工具，只允许本地源
        const allowedOrigins = [
            'http://localhost:3000',
            'http://localhost:3001',
            'http://127.0.0.1:3000',
            'http://127.0.0.1:3001',
            '*' // 开发时允许所有源
        ];

        if (allowedOrigins.includes('*') || !origin || allowedOrigins.includes(origin)) {
            res.setHeader('Access-Control-Allow-Origin', origin || '*');
        }

        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
        res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
        res.setHeader('Access-Control-Allow-Credentials', 'true');
        res.setHeader('Access-Control-Max-Age', '86400'); // 24小时

        // 处理预检请求
        if (req.method === 'OPTIONS') {
            res.status(200).end();
            return false; // 表示已处理，不应继续
        }

        return true; // 继续处理
    }

    /**
     * 基本请求验证
     */
    validateBasicRequest(req, res) {
        // 检查请求大小
        const contentLength = parseInt(req.headers['content-length'] || '0');
        if (contentLength > this.options.maxRequestSize) {
            res.status(413).json({
                error: 'Request entity too large',
                code: 'REQUEST_TOO_LARGE',
                maxSize: this.options.maxRequestSize,
                actualSize: contentLength
            });
            return false;
        }

        // 对于POST/PUT请求，基本的内容类型检查
        if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
            const contentType = req.headers['content-type'] || '';
            const allowedTypes = [
                'application/json',
                'application/x-www-form-urlencoded',
                'multipart/form-data',
                'text/plain'
            ];

            const hasValidContentType = allowedTypes.some(type =>
                contentType.toLowerCase().includes(type.toLowerCase())
            );

            if (contentType && !hasValidContentType) {
                res.status(415).json({
                    error: 'Unsupported media type',
                    code: 'UNSUPPORTED_MEDIA_TYPE',
                    supportedTypes: allowedTypes
                });
                return false;
            }
        }

        return true;
    }

    /**
     * 创建Express路由器专用的中间件
     */
    expressMiddleware() {
        return this.middleware();
    }

    /**
     * 为特定的HTTP方法创建中间件
     */
    methodMiddleware(methods = []) {
        return (req, res, next) => {
            if (methods.length > 0 && !methods.includes(req.method)) {
                res.status(405).json({
                    error: 'Method not allowed',
                    code: 'METHOD_NOT_ALLOWED',
                    allowedMethods: methods
                });
                return;
            }
            this.middleware()(req, res, next);
        };
    }

    /**
     * 验证API密钥（简化版本）
     */
    validateApiKey(apiKey, validKeys = []) {
        if (!apiKey) {
            return { valid: false, reason: 'Missing API key' };
        }

        if (validKeys.length === 0) {
            return { valid: true, reason: null }; // 如果没有配置密钥，则跳过验证
        }

        const isValid = validKeys.includes(apiKey);
        return {
            valid: isValid,
            reason: isValid ? null : 'Invalid API key'
        };
    }

    /**
     * 创建API密钥验证中间件
     */
    apiKeyMiddleware(validKeys = [], keyHeader = 'x-api-key') {
        return (req, res, next) => {
            const apiKey = req.headers[keyHeader];
            const validation = this.validateApiKey(apiKey, validKeys);

            if (!validation.valid) {
                res.status(401).json({
                    error: 'Unauthorized',
                    code: 'INVALID_API_KEY',
                    reason: validation.reason
                });
                return;
            }

            next();
        };
    }

    /**
     * 基本的请求日志记录
     */
    loggingMiddleware() {
        return (req, res, next) => {
            const start = Date.now();

            // 记录请求开始
            console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);

            // 监听响应结束
            res.on('finish', () => {
                const duration = Date.now() - start;
                console.log(`${new Date().toISOString()} - ${req.method} ${req.url} - ${res.statusCode} - ${duration}ms`);
            });

            next();
        };
    }

    /**
     * 获取当前配置
     */
    getConfig() {
        return { ...this.options };
    }

    /**
     * 更新配置
     */
    updateConfig(newOptions) {
        this.options = { ...this.options, ...newOptions };
    }
}

module.exports = SimpleAPISecurity;